////////////////////////////////////////////////////////////////////////////////
// Copyright 2006 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :
// AUTHOR           :
// DATE CREATE      :
// DESCRIPTION      :
//                  :
//                  :
//                  :
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  ----------------------------
// 2006/04/26   Ric Yik         1.0                 BugZilla #5535
// 2006/05/22   Cyris Liang     1.10                BugZilla #5845
// 2006/06/08   Ric Yik         1.0                 BugZilla #6173
//
////////////////////////////////////////////////////////////////////////////////
package com.erp.framework.util;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.FilterIterator;
import org.apache.commons.collections.Predicate;

import com.erp.app.common.ProjectConstants;
import com.erp.app.common.util.NullIterator;
import com.erp.framework.SimpleConstants;
import com.erp.framework.SimpleConstants.NumberFormats;
import com.erp.framework.util.logger.Logger;

public class CommonUtil implements SimpleConstants {

	// NOTE:
	// THIS CONSTANT FILE HAS BEEN CLEANED UP, PLEASE TRY TO USE EXISTING
	// DEFINED FUNCTIONS,
	// BEFORE YOU CREATE NEW FUNCTIONS!
	// AND IF ADD NEW FUNCTIONS, PLEASE ADD TO UNDER APPROPRIATE HEADINGS OF
	// THIS FILE.
	// THANKS! (- VICTOR)

	// Currently available headings/groups:
	//
	// Validation Utilities
	// Formatting Utilities
	// Date/Time Utilities
	// Number Utilities
	// Data Type Conversion Utilities
	// String Utilities
	// Other Unclassified Utilities

	/////////////////////////////////////////////////////////////////////////////////////
	// Append SQL String Utilities (e.g. addXXXXX())
	/////////////////////////////////////////////////////////////////////////////////////

    public static int max(int a, int b) {
        return (a < b) ? b : a;
    }

    public static String substring(String string, int startIndex, int endIndex) {
        return (string == null) ? null : (startIndex >= string.length() || startIndex > endIndex) ? "" : string.substring(startIndex, max(endIndex, string.length() - 1));
    }

	public static String toDate(String str) {
		if (str != null) {
			str = "TO_DATE('" + str + "', '" + ProjectConstants.ORACLE_INPUT_DATE_FORMAT + "') ";
		}
		return str;
	}

    public static String toNumber(String str) {
        if (str != null) {
            str = "TO_NUMBER('" + str + "') ";
        }
        return str;
    }

	public static String toUpper(String str) {
		return "UPPER(" + str + ")";
	}

	public static void addHdrEquals(StringBuffer whereClause, String column, String value) {
		if (!CommonUtil.isEmpty(value)) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(toUpper(column) + " = '" + value.toUpperCase().trim() + "' ");
		}
	}

	public static void addHdrLike(StringBuffer whereClause, String column, String value) {
		if (!CommonUtil.isEmpty(value)) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(toUpper(column) + " LIKE '%" + value.toUpperCase().trim() + "%' ");
		}
	}

	public static void addHdrBetween(StringBuffer whereClause, String column, String from, String to) {
		if (!CommonUtil.isEmpty(from)) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(toUpper(column) + " >= '" + from.toUpperCase().trim() + "' ");
		}
		if (!CommonUtil.isEmpty(to)) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(toUpper(column) + " <= '" + to.toUpperCase().trim() + "' ");
		}
	}

    public static void addHdrBetweenNumber(StringBuffer whereClause, String column, String from, String to) {
        if (from != null) {
            whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
            whereClause.append(column);
            whereClause.append(" >=  " + toNumber(from) + " ");
        }
        if (to != null) {
            whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
            whereClause.append(column);
            whereClause.append(" <= " + toNumber(to) + " ");
        }
    }

	public static void addHdrBetweenDate(StringBuffer whereClause, String column, String from, String to) {
		if (!CommonUtil.isEmpty(from)) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(column);
			whereClause.append(" >=  " + toDate(from) + " ");
		}
		if (!CommonUtil.isEmpty(to)) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(column);
			whereClause.append(" <= " + toDate(to) + " ");
		}
	}

    public static void addHdrBetweenDate(StringBuffer whereClause, String column, String from, String to, boolean truncateDate) {
        if (truncateDate) {
            column = "trunc(" + column + ")";
        }
        if (from != null) {
            whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
            whereClause.append(column);
            whereClause.append(" >=  " + toDate(from) + " ");
        }
        if (to != null) {
            whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
            whereClause.append(column);
            whereClause.append(" <= " + toDate(to) + " ");
        }
    }

	public static void addChildEquals(StringBuffer whereClause, String columnName, String value, String hdrTableOrAlias,
			String dtlTable, String docNo) {
		if (value != null) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(" EXISTS (SELECT 1 FROM " + dtlTable);
			whereClause.append(" WHERE " + hdrTableOrAlias + "." + docNo + " = " + dtlTable + "." + docNo);
			whereClause.append(" AND " + hdrTableOrAlias + ".COMPANY_CODE = " + dtlTable + ".COMPANY_CODE ");
			whereClause.append(" AND ").append(toUpper(columnName)).append(" = '");
			whereClause.append(value.trim().toUpperCase()).append("') ");
		}
	}

	public static void addChildEquals(StringBuffer whereClause, String columnName, String value, String hdrTableOrAlias,
			String dtlTable, String dtlDocNo, String anotherTable, String anotherDocNo) {

		if (!CommonUtil.isEmpty(value)) {

			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(" EXISTS (SELECT 1 FROM " + dtlTable + ", " + anotherTable);
			whereClause.append(" WHERE " + dtlTable + "." + dtlDocNo + " = " + hdrTableOrAlias + "." + dtlDocNo);
			whereClause.append(" AND " + dtlTable + ".COMPANY_CODE = " + hdrTableOrAlias + ".COMPANY_CODE ");
			whereClause.append(" AND " + dtlTable + "." + anotherDocNo + " = " + anotherTable + "." + anotherDocNo);
			whereClause.append(" AND " + dtlTable + ".COMPANY_CODE = " + anotherTable + ".COMPANY_CODE ");

			if (!CommonUtil.isEmpty(value)) {
				whereClause.append(" AND ").append(toUpper(anotherTable + "." + columnName)).append(" = '");
				whereClause.append(value.trim().toUpperCase() + "'");
			}

			whereClause.append(")");
		}

	}

	public static void addChildLike(StringBuffer whereClause, String columnName, String value, String hdrTableOrAlias,
			String dtlTable, String docNo) {
		if (value != null) {
			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(" EXISTS (SELECT 1 FROM " + dtlTable);
			whereClause.append(" WHERE " + hdrTableOrAlias + "." + docNo + " = " + dtlTable + "." + docNo);
			whereClause.append(" AND " + hdrTableOrAlias + ".COMPANY_CODE = " + dtlTable + ".COMPANY_CODE ");
			whereClause.append(" AND ").append(toUpper(columnName)).append(" like '%");
			whereClause.append(value.trim().toUpperCase()).append("%') ");
		}
	}

	public static void addChildBetween(StringBuffer whereClause, String columnName, String fromValue, String toValue,
			String hdrTableOrAlias, String dtlTable, String docNo) {
		if (!CommonUtil.isEmpty(fromValue) || !CommonUtil.isEmpty(toValue)) {

			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(" EXISTS (SELECT 1 FROM " + dtlTable);
			whereClause.append(" WHERE " + dtlTable + "." + docNo + " = " + hdrTableOrAlias + "." + docNo);
			whereClause.append(" AND " + dtlTable + ".COMPANY_CODE = " + hdrTableOrAlias + ".COMPANY_CODE ");

			if (!CommonUtil.isEmpty(fromValue)) {
				whereClause.append(" AND ").append(toUpper(columnName)).append(" >= '");
				whereClause.append(fromValue.trim().toUpperCase() + "'");
			}

			if (!CommonUtil.isEmpty(toValue)) {
				whereClause.append(" AND ").append(toUpper(columnName)).append(" <= '");
				whereClause.append(toValue.trim().toUpperCase() + "'");
			}
			whereClause.append(")");
		}

	}

	public static void addChildBetween(StringBuffer whereClause, String columnName, String fromValue, String toValue,
			String hdrTableOrAlias, String dtlTable, String dtlDocNo, String anotherTable, String anotherDocNo) {

		if (!CommonUtil.isEmpty(fromValue) || !CommonUtil.isEmpty(toValue)) {

			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(" EXISTS (SELECT 1 FROM " + dtlTable + ", " + anotherTable);
			whereClause.append(" WHERE " + dtlTable + "." + dtlDocNo + " = " + hdrTableOrAlias + "." + dtlDocNo);
			whereClause.append(" AND " + dtlTable + ".COMPANY_CODE = " + hdrTableOrAlias + ".COMPANY_CODE ");
			whereClause.append(" AND " + dtlTable + "." + anotherDocNo + " = " + anotherTable + "." + anotherDocNo);
			whereClause.append(" AND " + dtlTable + ".COMPANY_CODE = " + anotherTable + ".COMPANY_CODE ");

			if (!CommonUtil.isEmpty(fromValue)) {
				whereClause.append(" AND ").append(toUpper(anotherTable + "." + columnName)).append(" >= '");
				whereClause.append(fromValue.trim().toUpperCase() + "'");
			}

			if (!CommonUtil.isEmpty(toValue)) {
				whereClause.append(" AND ").append(toUpper(anotherTable + "." + columnName)).append(" <= '");
				whereClause.append(toValue.trim().toUpperCase() + "'");
			}
			whereClause.append(")");
		}

	}

	public static void addChildBetweenDate(StringBuffer whereClause, String columnName, String fromValue, String toValue,
			String hdrTableOrAlias, String dtlTable, String docNo) {
		if (!CommonUtil.isEmpty(fromValue) || !CommonUtil.isEmpty(toValue)) {

			whereClause.append(whereClause.length() == 0 ? "WHERE " : "AND ");
			whereClause.append(" EXISTS (SELECT 1 FROM " + dtlTable);
			whereClause.append(" WHERE " + dtlTable + "." + docNo + " = " + hdrTableOrAlias + "." + docNo);
			whereClause.append(" AND " + dtlTable + ".COMPANY_CODE = " + hdrTableOrAlias + ".COMPANY_CODE ");

			if (!CommonUtil.isEmpty(fromValue)) {
				whereClause.append(" AND ").append(toUpper(columnName)).append(" >= ");
				whereClause.append(" TO_DATE('" + fromValue.trim() + "', '" + ProjectConstants.ORACLE_INPUT_DATE_FORMAT + "') ");
			}

			if (!CommonUtil.isEmpty(toValue)) {
				whereClause.append(" AND ").append(toUpper(columnName)).append(" <= ");
				whereClause.append(" TO_DATE('" + toValue.trim() + "', '" + ProjectConstants.ORACLE_INPUT_DATE_FORMAT + "') ");
			}
			whereClause.append(")");
		}

	}

	/////////////////////////////////////////////////////////////////////////////////////
	// Validation Utilities (e.g. isXXXXX())
	/////////////////////////////////////////////////////////////////////////////////////

    public static boolean isValidNumber(String value, double minMaxValue, String minMaxFlag, boolean inclusive) {
        try {
            return NumberUtil.isValidNumber(value, minMaxValue, minMaxFlag, inclusive);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidNumber(String value, double minValue, boolean inclusive) {
        try {
            double d = Double.parseDouble(value);
            return (inclusive) ? (d >= minValue) : (d > minValue);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidNumber(String value, double minValue, boolean inclusive, int length, int precision) {
        try {
            if (!isValidNumber(value, length, precision)) {
                return false;
            }

            double d = Double.parseDouble(value);
            return (inclusive) ? (d >= minValue) : (d > minValue);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidNumber(String value, double minValue, double maxValue, boolean inclusive) {
        try {
            double d = Double.parseDouble(value);
            return (inclusive) ? (d >= minValue && d <= maxValue) : (d > minValue && d < maxValue);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidInteger(String value) {
        try {
            int i = Integer.parseInt(value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidBigDecimal(Object value) {
        if (value instanceof BigDecimal) return true;
        try {
            new BigDecimal(CommonUtil.getString(value));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidInteger(String value, int minValue, boolean inclusive) {
        try {
            int i = Integer.parseInt(value);
            return (inclusive) ? (i >= minValue) : (i > minValue);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidInteger(String value, int minValue, int maxValue, boolean inclusive) {
        try {
            int i = Integer.parseInt(value);
            return (inclusive) ? (i >= minValue && i <= maxValue) : (i > minValue && i < maxValue);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidInteger(String value, int minMaxValue, String minMaxFlag, boolean inclusive) {
        try {
            return NumberUtil.isValidInteger(value, minMaxValue, minMaxFlag, inclusive);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidDate(String value, String formatMask) {
        if (value == null) return false;
        if (value.length() != formatMask.length()) {
            return false;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(formatMask);
        formatter.setLenient(false);
        ParsePosition pos = new ParsePosition(0);
        java.util.Date d = formatter.parse(value, pos);

        return (pos.getErrorIndex() == -1 && pos.getIndex() == value.length());
    }

    public static boolean isValidDate(String inStr) {
    	if (isEmpty(inStr)) {
    		return false;
    	}
        String value = inStr.trim();

        if (value.length() != INPUT_DATE_FORMAT.length()) {
            return false;
        }
        return isValidDate(value, INPUT_DATE_FORMAT);
    }

    public static boolean isEmpty(String str) {
        return (str == null || str.trim().length() == 0);
    }

    public static boolean isEmptyIgnoreNegOne(String str) {
    	return ( (str == null) || (str.trim().length() == 0) || ("-1".equals(str)) );
    }

    public static boolean isEmpty(Object obj) {
        String str = String.valueOf(obj);
        return (str == null || str.equals("null") || str.trim().length() == 0);
    }

    private static boolean isAndNeeded(int x) {
        boolean needAnd = true;
        double epsilon = 0.0000000001;

        int numOfPlace = (int) Math.floor(Math.log((double) x) / Math.log(10.0)) + 1;

        int maxNum = (numOfPlace / 3) * 3;

        double pow = Math.pow(10.0, (double) maxNum);

        double y = x / pow;

        double diff = Math.abs(y - ((int) y));

        if (diff < epsilon) {
            int remainder = numOfPlace % 3;

            if (remainder == 2) {
                needAnd = false;
            }
        }

        return needAnd;
    }

    public static boolean isValidYear(String year) {
        return isValidPositiveInteger(year);
    }

    public static boolean isValidMonth(String month) {
        return isValidPositiveInteger(month) && Integer.parseInt(month) >= 1 && Integer.parseInt(month) <= 12;
    }

    public static boolean isNothing(Object o) {
        if (null != o) {
            if (o instanceof String)
                return "".equals(((String) o).trim());
        } else
            return true;
        return false;
    }


    private static boolean isZeroString(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != '0') {
                return false;
            }
        }
        return true;
    }

    public static boolean isValidPositiveNumberOrZero(String value) {
        return isValidPositiveNumber(value, true, NUMBER_LENGTH, NUMBER_PRECISION);
    }

    public static boolean isValidPositiveNumber(String value) {
        return isValidPositiveNumber(value, false, NUMBER_LENGTH, NUMBER_PRECISION);
    }

    public static boolean isValidAmount(String value) {
        return isValidPositiveNumber(value, true, NumberFormats.VALIDATE_AMOUNT_LENGTH, NumberFormats.VALIDATE_AMOUNT_PRECISION);
    }

    public static boolean isValidPrice(String value) {
        return isValidPositiveNumber(value, true, NumberFormats.VALIDATE_PRICE_LENGTH, NumberFormats.VALIDATE_PRICE_PRECISION);
    }

    public static boolean isValidMeasurement(String value) {
        return isValidPositiveNumber(value, true, NumberFormats.VALIDATE_MEASUREMENT_LENGTH, NumberFormats.VALIDATE_MEASUREMENT_PRECISION);
    }

    public static boolean isValidPercent(String value) {
        return isValidPositiveNumber(value, true, NumberFormats.VALIDATE_PERCENT_LENGTH, NumberFormats.VALIDATE_PERCENT_PRECISION);
    }

    public static boolean isValidNegativeChargesAmount(String value) {
        return isValidNegativeNumber(value, true, NumberFormats.VALIDATE_AMOUNT_LENGTH, NumberFormats.VALIDATE_AMOUNT_PRECISION);
    }

    public static boolean isValidPositiveChargesAmount(String value) {
        return isValidPositiveNumber(value, true, NumberFormats.VALIDATE_AMOUNT_LENGTH, NumberFormats.VALIDATE_AMOUNT_PRECISION);
    }

    public static boolean isValidPositiveNumber(String value, boolean includeZero, int length, int precision) {
        try {
            double d = Double.parseDouble(value);

            if (d < 0)
                return false;

            if (!includeZero && d == 0)
                return false;

            return isValidNumber(value, length, precision);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidNegativeNumberOrZero(String value) {
        return isValidNegativeNumber(value, true, NUMBER_LENGTH, NUMBER_PRECISION);
    }

    public static boolean isValidNegativeNumber(String value) {
        return isValidNegativeNumber(value, false, NUMBER_LENGTH, NUMBER_PRECISION);
    }

    public static boolean isValidNegativeNumber(String value, boolean includeZero, int length, int precision) {
        try {
            double d = Double.parseDouble(value);

            if (d > 0)
                return false;

            if (!includeZero && d == 0)
                return false;

            //return true;
            return isValidNumber(value, length, precision);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidNegativeInteger(String value) {
//        return isValidNegativeInteger(value, false);
    	return isValidNegativeNumber(value, false, NUMBER_LENGTH, 0);
    }

    public static boolean isValidNegativeIntegerOrZero(String value) {
    	return isValidNegativeNumber(value, true, NUMBER_LENGTH, 0);
    }

    public static boolean isValidPositiveInteger(String value) {
//        return isValidPositiveInteger(value, false);
    	return isValidPositiveNumber(value, false, NUMBER_LENGTH, 0);
    }

    public static boolean isValidPositiveIntegerOrZero(String value) {
//      return isValidPositiveInteger(value, false);
	  	return isValidPositiveNumber(value, true, NUMBER_LENGTH, 0);
    }

    public static boolean isValidNumber(String value) {
        return isValidNumber(value, NUMBER_LENGTH, NUMBER_PRECISION);
    }

    public static boolean isValidNumber(String str, int length, int precision) {
        if (isEmpty(str)) {
            return false;
        }

        try {
            BigDecimal d = new BigDecimal(str);
            return isValidNumber(d, length, precision);
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isValidNumber(Number num, int length, int precision) {
        if (num == null) {
            return false;
        }

        try {
            String str = num.toString();

            int lengthOfStr = str.length();
            int dp = str.indexOf(".");
            int integralPartLength = 0;
            int fractionalPartLength = 0;

            if (dp != -1) {
                integralPartLength = dp;
                fractionalPartLength = lengthOfStr - dp - 1;
            } else {
                integralPartLength = lengthOfStr;
            }

            if (fractionalPartLength > precision || integralPartLength > length - precision) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /////////////////////////////////////////////////////////////////////////////////////
    // Formatting Utilities (for NUMBER, DATE data types, to be displayed on Web Browser)
    /////////////////////////////////////////////////////////////////////////////////////

    public static String formatDefaultIntegerNoCom(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_INTEGER_NO_COM);
    }

    public static String formatDefaultDecimalNoCom(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_DECIMAL_NO_COM);
    }

    public static String formatDefaultDecimal(String inNum) {
        return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_DECIMAL);
    }

    public static String formatDefaultAmount(String inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_AMOUNT);
    }

    public static String formatDefaultMeasurement(String inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_MEASUREMENT);
    }

    public static String formatDefaultPrice(String inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_PRICE);
    }

    public static String formatDefaultPercent(String inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_PERCENT);
    }

    public static String formatDefaultInteger(String inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_INTEGER);
    }

    public static String formatDefaultDecimal(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_DECIMAL);
    }

    public static String formatDefaultAmount(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_AMOUNT);
    }

    public static String formatDefaultMeasurement(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_MEASUREMENT);
    }

    public static String formatDefaultPrice(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_PRICE);
    }

    public static String formatDefaultPercent(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_PERCENT);
    }

    public static String formatDefaultInteger(BigDecimal inNum) {
    	return formatNumber(inNum, NumberFormats.DISPLAY_FORMAT_INTEGER);
    }

    public static String formatBytes(long noOfBytes) {
        double bytesDivided = noOfBytes;
        String unit = "B";

        if (noOfBytes > 1024 * 1024 * 1024) {
            bytesDivided = noOfBytes * 1.0 / 1024 / 1024 / 1024;
            unit = "GB";
        } else if (noOfBytes > 1024 * 1024) {
            bytesDivided = noOfBytes * 1.0 / 1024 / 1024;
            unit = "MB";
        } else if (noOfBytes > 1024) {
            bytesDivided = noOfBytes * 1.0 / 1024;
            unit = "KB";
        }

        DecimalFormat df = new DecimalFormat(".#");
        return df.format(bytesDivided) + " " + unit;
    }

    public static String formatInputDate(String inStr){
    	return formatDateStr(inStr, DateFormats.INPUT_DATE_FORMAT, DateFormats.INPUT_DATE_FORMAT);
    }

    public static String formatInputDatetime(String inStr){
    	return formatDateStr(inStr, DateFormats.INPUT_DATETIME_FORMAT, DateFormats.INPUT_DATETIME_FORMAT);
    }

    public static String formatOutputDate(String inStr){
    	return formatDateStr(inStr, DateFormats.INPUT_DATE_FORMAT, DateFormats.OUTPUT_DATE_FORMAT);
    }

    public static String formatOutputDatetime(String inStr){
    	return formatDateStr(inStr, DateFormats.INPUT_DATETIME_FORMAT, DateFormats.OUTPUT_DATETIME_FORMAT);
    }

    public static String formatDateStr(String inStr, String origFormat, String destFormat) {
        if (isEmpty(inStr)) {
            return "";
        }

        if (isEmpty(origFormat)) {
            return "";
        }

        if (isEmpty(destFormat)) {
            return "";
        }

        SimpleDateFormat origSdf = new SimpleDateFormat(origFormat, DEFAULT_LOCALE);
        SimpleDateFormat destSdf = new SimpleDateFormat(destFormat, DEFAULT_LOCALE);
        try {
            if (isValidDate(inStr, origFormat)) {
                java.sql.Timestamp origTs = new java.sql.Timestamp(origSdf.parse(inStr).getTime());
                return destSdf.format(origTs);
            } else {
                return "";
            }
        } catch (Exception e) {
            Logger.logExceptions(e);
            return "";
        }
    }

    public static String getFormatMask(String str) {
        if (isEmpty(str)) {
            return null;
        }

        str = str.trim();

        String formatMask = null;

        if (str.length() == INPUT_DATE_FORMAT.length()) {
            formatMask = INPUT_DATE_FORMAT;
        } else if (str.length() == OUTPUT_DATE_FORMAT.length()) {
            formatMask = OUTPUT_DATE_FORMAT;
        }

        return formatMask;
    }



    public static String formatNumber0Places(String inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_0_PLACES);
    }

    public static String formatNumber2Places(String inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_2_PLACES);
    }

    public static String formatNumber4Places(String inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_4_PLACES);
    }

    public static String formatNumber6Places(String inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_6_PLACES);
    }

    public static String formatNumber0Places(BigDecimal inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_0_PLACES);
    }

    public static String formatNumber2Places(BigDecimal inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_2_PLACES);
    }

    public static String formatNumber4Places(BigDecimal inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_4_PLACES);
    }

    public static String formatNumber6Places(BigDecimal inNum) {
        return formatNumber(inNum, NUMBER_FORMAT_6_PLACES);
    }

    public static String formatNumber0Places(Object inNum) {
        return formatNumber(objToBigDecimal(inNum), NUMBER_FORMAT_0_PLACES);
    }

    public static String formatNumber2Places(Object inNum) {
        return formatNumber(objToBigDecimal(inNum), NUMBER_FORMAT_2_PLACES);
    }

    public static String formatNumber4Places(Object inNum) {
        return formatNumber(objToBigDecimal(inNum), NUMBER_FORMAT_4_PLACES);
    }

    public static String formatNumber6Places(Object inNum) {
        return formatNumber(objToBigDecimal(inNum), NUMBER_FORMAT_6_PLACES);
    }

    public static String formatNumber(String inNum, String format) {
    	try{
    		return formatNumber(new BigDecimal(inNum), format);
    	}catch(Exception e){
    		return "";
    	}
    }

    public static String formatNumber(BigDecimal inNum, String format) {
        if (inNum == null) {
            return "";
        }

        if (isEmpty(inNum)) {
            return "";
        }

        if (isEmpty(format)) {
            return "";
        }

        try{
	        DecimalFormat myFormatter = new DecimalFormat(format);
	        return myFormatter.format(inNum.doubleValue());
        } catch(Exception e){
        	return "";
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////
    // Date/Time Utilities
    /////////////////////////////////////////////////////////////////////////////////////

    public static boolean isLeapYear(int year){
    	if( (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)) ) {
    		return true;
    	} else {
    		return false;
    	}
    	/*
    	CREATE OR REPLACE FUNCTION isLeapYear(i_year NUMBER) RETURN boolean AS
		BEGIN
		  -- A year is a leap year if it is evenly divisible by 4
		  -- but not if it's evenly divisible by 100
		  -- unless it's also evenly divisible by 400

		   IF mod(i_year, 400) = 0 OR ( mod(i_year, 4) = 0 AND mod(i_year, 100) != 0) THEN
		      return TRUE;
		   ELSE
		      return FALSE;
		   END IF;
		END;
		/
    	*/
    }

    public static long getCurrentTime() {
        return (new java.util.Date()).getTime();
    }

    public static java.util.Date getCurrentDate() {
        return new java.util.Date(System.currentTimeMillis());
    }


	public static Date addDays(String src, int days) {
		Date date;
		if (src == null)
			return null;

		date = stringToDate(src);

		if (date == null)
			date = stringToDate(src);

		return addDays(date, days);
	}

	public static Date addDays(Date src, int days) {
		if (src == null)
			return null;

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(src);
		calendar.add(Calendar.DATE, days);

		return calendar.getTime();
	}

	/////////////////////////////////////////////////////////////////////////////////////
    // Number Utilities (int/long/BigDecimal/BigInteger etc.)
    /////////////////////////////////////////////////////////////////////////////////////


    public static boolean bigDecimalEquals(BigDecimal b1, BigDecimal b2) {
        if ((b1.equals(b2)) && (b2.equals(b1)))
            return true;
        else
            return false;
    }

    public static boolean bigDecimalCompare(BigDecimal b1, BigDecimal b2) {
        if ((b1.compareTo(b2) == 0) && (b2.compareTo(b1)) == 0)
            return true;
        else
            return false;
    }


    public static BigDecimal nvl(Object obj) {
        return getBigDecimal(obj);
    }

    static public BigDecimal getBigDecimal(Object o) {
        BigDecimal bi = new BigDecimal("0");
        if (null != o) {
            if (o instanceof Number) {
                if (o instanceof BigDecimal) return (BigDecimal) o;
                bi = new BigDecimal(o.toString());
            } else if (o instanceof String) {
                try {
                    bi = new BigDecimal((String) o);
                } catch (Throwable e) {
                }
            }
        }
        return bi;
    }

    public static int stringNumberCompareTo(String val1, String val2) {
        if (val1 == val2) {
            return 0;
        }
        return ((new BigDecimal(val1)).compareTo(new BigDecimal(val2)));
    }

    public static double roundDouble(double val, int places) {
        long factor = (long) Math.pow(10, places);
        val = val * factor;
        long tmp = Math.round(val);
        double rslt = (double) tmp / factor;
        return rslt;
    }



	/////////////////////////////////////////////////////////////////////////////////////
    // Data Type Conversion Utilities (e.g. dateToString(), stringToDate(),
	// bigDecimalToString(), stringToBigDecimal())
    /////////////////////////////////////////////////////////////////////////////////////


    public static java.util.Date stringToDate(String value, String formatMask) {
        if (isEmpty(value))
            return null;
        SimpleDateFormat formatter = new SimpleDateFormat(formatMask);
        formatter.setLenient(false);
        ParsePosition pos = new ParsePosition(0);
        java.util.Date date = formatter.parse(value, pos);
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length())
            return date;
        else
            return null;
    }

    public static java.util.Date stringToDate(String str, String format, Locale locale) throws ParseException {
        return ConvertUtil.stringToDate(str, format, locale);
    }

    public static java.util.Date searchFormStringToDate(String value) {
        if (isEmpty(value))
            return null;
        if (value.length() == 8) {
            return stringToDate(value, INPUT_DATE_FORMAT);
//        } else if (value.length() == 10) {
//            return stringToDate(value, DATE_WITH_SLASH_FORMAT_MASK);
        } else {
            return null;
        }

    }

    public static java.util.Date stringToDate(String value) {
        return stringToDate(value, INPUT_DATE_FORMAT);
    }


    public static java.util.Date strToUtilDate(String strDate, String format) throws java.text.ParseException {
        if (strDate == null || strDate.trim().length() < 1) {
            return null;
        } else {
            SimpleDateFormat smf = new SimpleDateFormat(format);
            return smf.parse(strDate);
        }
    }

    public static String utilDateToStr(java.util.Date date, String format) {
        if (date == null) {
            return null;
        } else {
            SimpleDateFormat smf = new SimpleDateFormat(format);
            return smf.format(date);
        }
    }

    public static final String convertDateFormat(String input, String origFormat, String newFormat) {
    	if (isEmpty(input) || isEmpty(origFormat) || isEmpty(newFormat)) {
    		return "";
    	}

    	if (!isValidDate(input, origFormat)) {
    		return "";
    	} else {
    		Date tempDate = stringToDate(input, origFormat);

    		return dateToString(tempDate, newFormat);
    	}
    }
    public static String zeroToString(String str) {
        return (str == null) ? "0" : str;
    }

    public static String nilToString(String str) {
        if (str == null) {
            return "";
        } else if (str.equalsIgnoreCase(SimpleConstants.DB_NIL)) {
            return "";
        } else {
            return str;
        }
    }

    public static String nullStrToString(String str) {
        return (str == null || "null".equals(str)) ? "" : str;
    }

    public static String nullToString(String str, String dftStr) {
        return (str == null) ? dftStr : str;
    }

    public static String nullToString(String str) {
        return (str == null) ? "" : str;
    }

    public static String nullToString(Object obj) {
        return (obj == null) ? "" : obj.toString();
    }

    public static String nullDateToHyphen(Object obj){
    	if(obj == null){
    		return "-";
    	}

    	String str = obj.toString();
        if (str.trim().equals("")) {
            return "-";
        } else {
            return str;
        }
    }

    public static String nilToHyphen(Object obj){
    	if(obj == null){
    		return "";
    	}

    	String str = obj.toString();

        if (str.equals(SimpleConstants.DB_NIL)) {
            return "-";
        } else {
            return str;
        }
    }

    public static String nilToString(Object obj){
    	if(obj == null){
    		return "";
    	}

    	String str = obj.toString();

        if (str.equals(SimpleConstants.DB_NIL)) {
            return "";
        } else {
            return str;
        }
    }

    public static double objToDouble(Object inObj) {
        try {
            String inStr = String.valueOf(inObj);
            if (inStr != null && !inStr.equals("null") && !inStr.equals(""))
                return Double.parseDouble(inStr);
            return 0;
        } catch (Exception e) {
            return 0;
        }
    }

    public static String objToString(Object obj) {
        if (obj == null)
            return "";
        else
            return (String) obj;
    }

    public static BigDecimal objToBigDecimal(Object obj) {
        if (obj == null)
            return new BigDecimal("0");
        else
            return (BigDecimal) obj;
    }

    public static String toQuotedList(ArrayList val) {
        String ret = "";
        if (val != null) {
            String[] val2 = (String[]) val.toArray(new String[0]);
            ret = toQuotedList(val2);
        }
        return (ret);
    }

    public static String toQuotedList(String[] val) {
        StringBuffer sb = new StringBuffer();
        if (val != null && val.length > 0) {
            for (int i = 0; i < val.length; i++) {
                String currentVal = val[i];
                if (!isEmpty(currentVal)) {
                    if (sb.length() > 0)
                        sb.append(",");
                    sb.append("\"" + currentVal + "\"");
                }
            }
        }
        return (sb.length() > 0 ? sb.toString() : null);
    }

    public static String toDelimitedList(Collection list) {
        return toDelimitedList(list, "'");
    }

    public static String toDelimitedList(Collection list, String delimiter) {
        StringBuffer sb = new StringBuffer();

        if (list == null || list.size() == 0)
            return "";

        Iterator it = list.iterator();

        while (it.hasNext()) {
            String value = (String) it.next();
            if (sb.length() > 0)
                sb.append(",");
            sb.append(delimiter + nullToString(value) + delimiter);
        }

        return sb.toString();
    }

    public static String toList(String[] val) {
        StringBuffer sb = new StringBuffer();
        if (val != null && val.length > 0) {
            for (int i = 0; i < val.length; i++) {
                String currentVal = val[i];
                if (!isEmpty(currentVal)) {
                    if (sb.length() > 0)
                        sb.append(", ");
                    sb.append(currentVal);
                }
            }
        }
        return (sb.length() > 0 ? sb.toString() : null);
    }

    public static Integer strToInteger(String strInt) {
        Integer rtnInt = null;
        try {
            if (strInt != null && strInt.trim().length() > 0) {
                rtnInt = Integer.valueOf(strInt);
            }
        } catch (Exception e) {
        }
        return rtnInt;
    }

    public static String timestampToString(Timestamp ts) {
        if (ts == null)
            return null;

        return ts.toString();
    }

    public static String timestampToString(Timestamp ts, String formatMask) {
        if (ts == null) {
            return "";
        }

        if (isEmpty(formatMask)) {
            return "";
        }

        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(formatMask, DEFAULT_LOCALE);
        return sdf.format(ts);
    }

    public static Timestamp stringToTimestamp(String value) {
        Timestamp retTs = null;

        if (isEmpty(value))
            return null;
        try {
            retTs = Timestamp.valueOf(value);
        } catch (Exception e) {
            Logger.logExceptions(e);
        }

        return retTs;

    }

    public static Timestamp stringToTimestamp(String value, String formatMask) {
        if (isEmpty(value))
            return null;

        Timestamp retVal = null;

        try {
            java.util.Date inValue = CommonUtil.stringToDate(value, formatMask);
            retVal = (inValue == null) ? null : new Timestamp(inValue.getTime());
        } catch (Exception e) {
            return null;
        }

        return retVal;
    }

    public static BigDecimal strToBigDecimal(String strBd) {
        if (strBd == null || strBd.trim().length() < 1) {
            return null;
        } else {
            return new BigDecimal(strBd);
        }
    }

    public static String bigDecimalToStr(BigDecimal bd) {
        if (bd != null) {
            return bd.toString();
        } else {
            return null;
        }
    }

    public static BigInteger strToBigInteger(String strInt) {
//        BigInteger rtnInt = null;
//        try {
//            if (strInt != null && strInt.trim().length() > 0) {
//                rtnInt = new BigInteger(strInt);
//            }
//        } catch (Exception e) {
//        }
//        return rtnInt;
    	return strToBigInteger(strInt, false);
    }

    public static BigInteger strToBigIntegerWithZero(String strInt) {
    	return strToBigInteger(strInt, true);
    }

    public static BigInteger strToBigInteger(String strInt, boolean returnZero) {
        BigInteger rtnInt = null;
        try {
        	if( (strInt == null) || (strInt.trim().length() == 0) ){
        		if(returnZero){
        			return new BigInteger("0");
        		}
        	} else {
                rtnInt = new BigInteger(strInt);
            }
        } catch (Exception e) {
    		if(returnZero){
    			return new BigInteger("0");
    		}
        }
        return rtnInt;
    }

    public static String bigIntegerToStr(BigInteger bInt) {
        String rtn = null;
        try {
            if (bInt != null) {
                rtn = bInt.toString();
            }
        } catch (Exception e) {
            Logger.logExceptions(e);
        }
        return rtn;
    }

    public static String integerToStr(Integer inInt) {
        String rtn = null;
        try {
            if (inInt != null) {
                rtn = inInt.toString();
            }
        } catch (Exception e) {
            Logger.logExceptions(e);
        }
        return rtn;
    }


    public static String convert(String number_str) {
        BigDecimal num = null;
        try {
            num = new BigDecimal(number_str);
        } catch (Exception e) {
            Logger.logExceptions(e);
            return null;
        }

        String integral_part = String.valueOf(num.intValue());
        String tmp = num.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
        String fractional_part = tmp.substring(tmp.length() - 2);

        if (integral_part.length() > 9) {
            return number_str;
        }

        if (isZeroString(number_str)) {
            return "Zero";
        } else if (!isZeroString(fractional_part)) {
            return toWords(integral_part) + " And Cents " + toWords(fractional_part).trim();
        } else {
            StringBuffer buf = new StringBuffer(toWords(integral_part).trim());
            String partial = null;
            boolean okayed = false;
            int pos = 0;
            for (int i = 0, j; i < integral_part.length(); i++) {
                j = integral_part.length() - i - 1;
                partial = toWords(integral_part.substring(j)).trim();
                if (partial.length() < buf.length() && partial.length() > 1) {
                    if (partial.equals(buf.substring(buf.length() - partial.length()))) {
                        if (i == 0) {
                            okayed = true;
                            pos = buf.length() - partial.length();
                        } else {
                            if (isAndNeeded(Integer.parseInt(integral_part))) {
                                if (i > 1 && okayed)
                                    buf.insert(pos, "And ");
                                buf.insert(buf.length() - partial.length(), "And ");
                                okayed = false;
                            }
                            break;
                        }
                    }
                }
            }

            if (isAndNeeded(Integer.parseInt(integral_part))) {
                if (okayed && integral_part.length() > 2)
                    buf.insert(pos, "And ");
            }
            return buf.toString();
        }
    }

    public static String convert(Number num) {
        return (convert(num + ""));
    }

    public static BigDecimal strToBigDecimalForInquiryForm(String strBd) {
        if (strBd == null || strBd.trim().length() < 1) {
            return new BigDecimal("0");
        } else {
            return new BigDecimal(strBd);
        }
    }

    public static String dateToString(java.sql.Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(OUTPUT_DATE_FORMAT, DEFAULT_LOCALE);

        return formatter.format(date);
    }

    public static String dateToString(java.sql.Date date, String formatMask) {
        if (date == null) {
            return "";
        }

        if (isEmpty(formatMask)) {
            return "";
        }

        SimpleDateFormat formatter = new SimpleDateFormat(formatMask, DEFAULT_LOCALE);
        return formatter.format(date);
    }

	public static String dateToString(java.util.Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(OUTPUT_DATE_FORMAT, DEFAULT_LOCALE);

        return formatter.format(date);
    }

    public static String dateToString(java.util.Date date, String formatMask) {
        if (date == null) {
            return "";
        }

        if (isEmpty(formatMask)) {
            return "";
        }

        SimpleDateFormat formatter = new SimpleDateFormat(formatMask, DEFAULT_LOCALE);
        return formatter.format(date);
    }

    public static String addMonth(java.util.Date date, int addBy) {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(GregorianCalendar.MONTH, addBy);

		return dateToString(calendar.getTime());
	}

    public static BigDecimal stringToBigDecimal(String strBd) {
    	try{
	        if (strBd == null || strBd.trim().length() < 1) {
	            return new BigDecimal("0");
	        } else {
	            return new BigDecimal(strBd);
	        }
    	}catch(Exception e){
    		return new BigDecimal("0");
    	}
    }

    public static BigInteger stringToBigInteger(String strBd) {
    	try{
	        if (strBd == null || strBd.trim().length() < 1) {
	            return new BigInteger("0");
	        } else {
	            return new BigInteger(strBd);
	        }
    	}catch(Exception e){
    		return new BigInteger("0");
    	}
    }

    /////////////////////////////////////////////////////////////////////////////////////
    // String Utilities
    /////////////////////////////////////////////////////////////////////////////////////

    public static int countStringToken(String str, char token){
    	if((str == null) || (str.length() == 0)) {
    		return 0;
    	}

    	int count = 0;
    	for(int i = 0; i < str.length(); i++){
    		if(token == str.charAt(i)) {
    			count++;
    		}
    	}

    	return count;
    }

    public static String toWords(String num_str) {
        int num_str_len = num_str.length();
        if (num_str_len > 6) {
            return toWords(num_str.substring(0, num_str_len - 6)) + "Million " + toWords(num_str.substring(num_str_len - 6));
        } else if (num_str_len > 3) {
            return ((isZeroString(num_str.substring(0, num_str_len - 3))) ? "" : toWords(num_str.substring(0, num_str_len - 3))
                    + "Thousand ")
                    + toWords(num_str.substring(num_str_len - 3));
        } else if (num_str_len > 2) {
            return ((isZeroString(num_str.substring(0, num_str_len - 2))) ? "" : toWords(num_str.substring(0, num_str_len - 2))
                    + "Hundred ")
                    + toWords(num_str.substring(num_str_len - 2));
        } else if (num_str_len == 2) {
            if (num_str.charAt(0) == '1' && num_str.charAt(1) != '0') {
                switch (num_str.charAt(1)) {
                    case '1':
                        return "Eleven ";
                    case '2':
                        return "Twelve ";
                    case '3':
                        return "Thirteen ";
                    case '4':
                        return "Fourteen ";
                    case '5':
                        return "Fifteen ";
                    case '6':
                        return "Sixteen ";
                    case '7':
                        return "Seventeen ";
                    case '8':
                        return "Eighteen ";
                    case '9':
                        return "Nineteen ";
                    default:
                        return " ";
                }
            } else {
                switch (num_str.charAt(0)) {
                    case '0':
                        return toWords(num_str.substring(1));
                    case '1':
                        return "Ten ";
                    case '2':
                        return "Twenty " + toWords(num_str.substring(1));
                    case '3':
                        return "Thirty " + toWords(num_str.substring(1));
                    case '4':
                        return "Forty  " + toWords(num_str.substring(1));
                    case '5':
                        return "Fifty " + toWords(num_str.substring(1));
                    case '6':
                        return "Sixty " + toWords(num_str.substring(1));
                    case '7':
                        return "Seventy " + toWords(num_str.substring(1));
                    case '8':
                        return "Eighty " + toWords(num_str.substring(1));
                    case '9':
                        return "Ninety " + toWords(num_str.substring(1));
                    default:
                        return " ";
                }
            }
        } else {
            switch (num_str.charAt(0)) {
                case '1':
                    return "One ";
                case '2':
                    return "Two ";
                case '3':
                    return "Three ";
                case '4':
                    return "Four ";
                case '5':
                    return "Five ";
                case '6':
                    return "Six ";
                case '7':
                    return "Seven ";
                case '8':
                    return "Eight ";
                case '9':
                    return "Nine ";
                default:
                    return " ";
            }
        }
    }

    public static String toValidFileName(String name) {
        return toValidFileName(name, 256);
    }

    public static String toValidFileName(String name, int length) {
        if (isEmpty(name))
            return "new_file";

        StringBuffer sb = new StringBuffer();
        char ch;
        int ascii;

        for (int i = 0; i < name.length(); i++) {
            ch = name.charAt(i);
            ascii = (int) ch;

            if ((ascii >= 48 && ascii <= 57) || ascii == 46 || ascii == 95 || (ascii >= 65 && ascii <= 90)
                    || (ascii >= 97 && ascii <= 122)) {
                sb.append(ch);
            }
        }

        return sb.length() > length ? sb.substring(0, length - 1) : sb.toString();
    }

    public static String toCSVToken(String str) {
        if (isEmpty(str))
            return "";

        boolean hasComma = (str.indexOf(',') != -1);
        boolean hasDQuote = (str.indexOf('"') != -1);
        boolean hasEnter = ((str.indexOf('\n') != -1) || (str.indexOf('\r') != -1));

        if (!hasComma && !hasDQuote) {
            if (!hasEnter) {
                return str;
            } else {
                return "\"" + str + "\"";
            }
        }

        StringBuffer sb = new StringBuffer(str);
        if (hasDQuote) {
            int idx = -2;
            while ((idx = sb.toString().indexOf('"', idx + 2)) != -1) {
                sb = sb.insert(idx, '"');
            }
        }
        sb.insert(0, '"');
        sb.append('"');
        return sb.toString();
    }

    public static String encodeString(String str, String enc) {
        if (str == null)
            return null;
        try {
            return new String(str.getBytes(enc), "8859_1");
        } catch (java.io.UnsupportedEncodingException nse) {
            return str;
        }
    }

    public static String decodeString(String str, String enc) {
        if (str == null)
            return null;
        try {
            return new String(str.getBytes("8859_1"), enc);
        } catch (java.io.UnsupportedEncodingException nse) {
            return str;
        }
    }

    public static String trimString(String str) {
        if (str == null) {
            return null;
        } else {
            return str.trim();
        }
    }


    public static String stringRpl(String instring, String replstr, String replstr1) {
        int length = instring.length();
        int length1 = replstr.length();
        int pos = instring.indexOf(replstr);
        String new_string = "";
        String cut_string = instring;
        while (pos >= 0) {
            new_string += cut_string.substring(0, pos);
            new_string += replstr1;
            cut_string = cut_string.substring(pos + length1);
            pos = cut_string.indexOf(replstr);
        }

        String full_string = new_string + cut_string;
        return full_string;
    }

    public static String chopDecimalPlaces(String inStr, int numOfDecimal) {
        int dotIndex = -1;

        if (!CommonUtil.isValidNumber(inStr)) {
            return inStr;
        }

        dotIndex = inStr.indexOf(".");
        if (dotIndex == -1) {
            return inStr;
        }

        if ((inStr.length() - dotIndex) < (numOfDecimal + 1)) {
            return inStr;
        }

        return inStr.substring(0, dotIndex + numOfDecimal + 1);
    }

    public static String addLeadingSpace(String inStr, int numOfSpace) {
        String temp = "";

        inStr = nullToString(inStr);

        if (numOfSpace <= 0) {
            return inStr;
        }

        for (int i = 0; i < numOfSpace; i++) {
            temp += " ";
        }

        return (temp + inStr);
    }

    public static String addTrailingSpace(String inStr, int numOfSpace) {
        String temp = "";

        inStr = nullToString(inStr);

        if (numOfSpace <= 0) {
            return inStr;
        }

        for (int i = 0; i < numOfSpace; i++) {
            temp += " ";
        }

        return (inStr + temp);
    }

    public static String[] split(String inStr, String delim) {
        if (inStr == null || delim == null) return new String[0];
        StringTokenizer st = new StringTokenizer(inStr, delim);
        int count = st.countTokens();
        if (count <= 0) {
            return new String[0];
        }

        String[] returnStr = new String[count];
        int i = 0;

        while (st.hasMoreTokens()) {
            returnStr[i++] = st.nextToken();
        }

        return returnStr;
    }


    public static String sqlEncode(String inStr) {
        if (inStr == null)
            return inStr;

        return stringRpl(inStr, "\u0027", "''");
    }

    public static boolean stringEquals(String str1, String str2) {
        if ((str1.equals(str2)) && (str2.equals(str1)))
            return true;
        else
            return false;
    }

    public static boolean stringEqualsIgnoreCase(String str1, String str2) {
        if ((str1.equalsIgnoreCase(str2)) && (str2.equalsIgnoreCase(str1)))
            return true;
        else
            return false;
    }

    public static String intLpad(int num, int size, String mask) {
        String result = "";
        if (size == 0) {
            return "";
        }

        if (mask == null) {
            return "";
        }

        String tmp = String.valueOf(num);
        int numToFill = size - tmp.length();
        for (int i = 0; i < numToFill; i++) {
            result = mask + result;
        }
        result = result + tmp;

        return result;
    }

    public static String lpad(BigDecimal num, int size, String mask) {
        String result = "";

        if (num == null) {
            Logger.warn("lpad(), Input number is null.");
            return "";
        }

        if (size == 0) {
            Logger.warn("lpad(), Input size is 0.");
            return "";
        }

        if (mask == null) {
            Logger.warn("lpad(), Input mask is null.");
            return "";
        }

        String tmp = String.valueOf(num);
        int numToFill = size - tmp.length();
        for (int i = 0; i < numToFill; i++) {
            result = mask + result;
        }
        result = result + tmp;

        return result;
    }

    public static String rpad(BigDecimal num, int size, String mask) {
        String result = "";

        if (num == null) {
            Logger.warn("rpad(), Input number is null.");
            return "";
        }

        if (size == 0) {
            Logger.warn("rpad(), Input size is 0.");
            return "";
        }

        if (mask == null) {
            Logger.warn("rpad(), Input mask is null.");
            return "";
        }

        String tmp = String.valueOf(num);
        int numToFill = size - tmp.length();
        for (int i = 0; i < numToFill; i++) {
            result = mask + result;
        }
        result = tmp + result;

        return result;
    }

    public static String concatString(String str1, String str2, String delimiter) {
        String rslt = "";

        String str_1 = CommonUtil.nullToString(str1).trim();
        String str_2 = CommonUtil.nullToString(str2).trim();

        if (CommonUtil.isEmpty(str1))
            return str2;

        if (CommonUtil.isEmpty(str2))
            return str1;

        if (CommonUtil.isEmpty(delimiter))
            rslt = str_1 + str_2;
        else {
            if ((str_1.length() > 1 && str_1.substring(str_1.length() - 1, str_1.length()).equals(delimiter.trim()))
                    || (str_2.length() > 1 && str_2.substring(0, 1).equals(delimiter.trim())))
                rslt = str_1 + str_2;
            else
                rslt = str_1 + delimiter + str_2;
        }

        return rslt;
    }

    /////////////////////////////////////////////////////////////////////////////////////
    // Other Unclassified Utilities
    /////////////////////////////////////////////////////////////////////////////////////

    public static Iterator getIterator(Collection c) {
        return (c != null) ? c.iterator() : new NullIterator();
    }

    public static String getNextSequence(Collection c, String seqPropertyName) throws java.lang.IllegalAccessException,
            java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException {
        return getNextSequence(getIterator(c), seqPropertyName);
    }

    public static String getNextSequence(Iterator it, String seqPropertyName) throws java.lang.IllegalAccessException,
            java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException {

        int maxSeqNo = 1;
        if (it != null) {
            int currentSeqNo = -1;
            while (it.hasNext()) {
                Object obj = it.next();
                Object value = PropertyUtils.getSimpleProperty(obj, seqPropertyName);
                if (value instanceof String) {
                    String seqNo = (String) value;
                    try {
                        currentSeqNo = Integer.parseInt(seqNo);
                    } catch (Exception e) {
                        continue;
                    }
                    if (currentSeqNo >= maxSeqNo) {
                        maxSeqNo = currentSeqNo + 1;
                    }
                }
            }
        }

        return String.valueOf(maxSeqNo);
    }

    public static String getNextSequence(Collection c, String seqPropertyName, String defaultValue) {
        try {
            return getNextSequence(c, seqPropertyName);
        } catch (IllegalAccessException e) {
            return defaultValue;
        } catch (NoSuchMethodException e) {
            return defaultValue;
        } catch (InvocationTargetException e) {
            return defaultValue;
        }
    }



    public static String getNextSequence(Iterator it, String seqPropertyName, String defaultValue) {
        try {
            return getNextSequence(it, seqPropertyName);
        } catch (IllegalAccessException e) {
            return defaultValue;
        } catch (NoSuchMethodException e) {
            return defaultValue;
        } catch (InvocationTargetException e) {
            return defaultValue;
        }
    }

    public static String getDocumentSequence(int count) throws Exception {
        return getDocumentSequence(count, 26);
    }

    public static String getDocumentSequence(int count, int radix) throws Exception {
        StringBuffer rslt = new StringBuffer("");

        if (count <= 0)
            return rslt.toString();

        if (count < radix + 1)
            return String.valueOf(count);

        int multiplier = (int) Math.floor(count / radix);
        int remainder = count % radix;

        if (remainder == 0) {
            if (multiplier > radix) {
                rslt.append(getDocumentSequence(multiplier - 1) + "," + 26);
                return rslt.toString();
            } else
                return multiplier - 1 + "," + 26;
        }

        if (multiplier > radix) {
            rslt.append(getDocumentSequence(multiplier) + "," + getDocumentSequence(remainder));
            return rslt.toString();
        }
        return multiplier + "," + getDocumentSequence(remainder);
    }

    public static int decodeDocumentSequence(String seq, int radix) throws Exception {
        int rslt = 0;

        StringTokenizer tokens = new StringTokenizer(seq, ",");
        int counter = tokens.countTokens() - 1;

        while (counter >= 0) {
            rslt += Math.pow(radix, counter--) * Integer.parseInt(tokens.nextToken());
        }

        return rslt + 1;
    }

    public static String getDataAccessSecurityWhereClause(ArrayList userSecurityList) {
        StringBuffer sb = new StringBuffer();

        Collection userDataAccessInfo = userSecurityList;

        if (userDataAccessInfo == null) {
            sb.append("''");
            return sb.toString();
        }

        Iterator it = userDataAccessInfo.iterator();
        HashMap map = null;
        String dept = "";

        while (it.hasNext()) {
            map = (HashMap) it.next();
            dept = (String) map.get("DEPT");

            if (map == null)
                continue;

            if (sb.length() > 0)
                sb.append(", ");

            sb.append("'");
            sb.append(dept == null ? "" : dept);
            sb.append("'");
        }

        if (sb.length() == 0)
            sb.append("''");
        return sb.toString();
    }

    public static String getCodeValueFromList(Collection c, String value, String valueProperty, String labelProperty)
            throws java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException {

        String label = "";
        if (c != null) {
            label = getCodeValueFromList(c.iterator(), value, valueProperty, labelProperty);
        }
        return label;
    }

    public static String getCodeValueFromList(Iterator it, String value, String valueProperty, String labelProperty)
            throws java.lang.IllegalAccessException, java.lang.NoSuchMethodException, java.lang.reflect.InvocationTargetException {

        String label = "";

        if (valueProperty == null || valueProperty.trim().equals("") || labelProperty == null || labelProperty.trim().equals("")) {
            return label;
        }

        if (it != null) {
            for (; it.hasNext();) {
                Object obj = it.next();
                Object currentValue = PropertyUtils.getSimpleProperty(obj, valueProperty);
                if (currentValue == null)
                    continue;
                if (currentValue instanceof String)
                    currentValue = (String) currentValue;
                else
                    currentValue = currentValue.toString();
                if (currentValue.equals(value)) {
                    label = (String) PropertyUtils.getSimpleProperty(obj, labelProperty);
                    break;
                }
            }
        }

        return label;
    }

    public static String getAppropriateNumberFormat(String number) {
        String formatString = NUMBER_FORMAT_6_PLACES;
        int indexOf = number.indexOf(".");
        int decimalPlaceLength = (indexOf >= 0) ? number.substring(indexOf).length() : 0;
        switch (decimalPlaceLength) {
        case 2:
            formatString = NUMBER_FORMAT_2_PLACES;
            break;
        case 4:
            formatString = NUMBER_FORMAT_4_PLACES;
            break;
        case 6:
            formatString = NUMBER_FORMAT_6_PLACES;
            break;
        case 0:
        default:
            formatString = NUMBER_FORMAT_0_PLACES;
            break;
        }
        return formatNumber(number, formatString);
    }

    public static String toTrimmedUpperCase(String s) {
        return (s != null) ? s.trim().toUpperCase() : s;
    }

    public static String toCode(String s) {
        return toTrimmedUpperCase(s);
    }

    public static String trim(String s) {
        return (s != null) ? s.trim() : s;
    }

    public static String getString(String value, String defaultValue) {
        return (!isEmpty(value)) ? value : defaultValue;
    }

    public static String getString(String value) {
        return getString(value, "");
    }

    public static String getString(Object value) {
        return (value == null) ? "" : value.toString();
    }

    public static BigDecimal getBigDecimal(BigDecimal value) {
        return (value == null) ? new BigDecimal(0) : value;
    }

    public static Exception getTargetExecption(InvocationTargetException e) {
        return ((e.getTargetException() instanceof Exception) ? (Exception) e.getTargetException() : e);
    }

    public static Map getMap(Map map) {
        return (map == null) ? Collections.EMPTY_MAP : map;
    }

    public static String join(String[] objects, String qualifier, String seperator) {
        return join(Arrays.asList(objects).iterator(), qualifier, seperator);
    }

    public static List getList(Iterator iterator) {
        List result = new ArrayList();
        if (iterator == null) return result;
        while (iterator.hasNext()) {
            result.add(iterator.next());
        }
        return result;
    }

    public static Set getSet(Iterator iterator) {
        return new HashSet(getList(iterator));
    }

    public static Iterator getDistinctIterator(Iterator iterator) {
        return CommonUtil.getIterator(getSet(iterator));
    }

    public static Iterator filterEmpty(Iterator iterator) {
        return new FilterIterator(iterator, new Predicate() {

            public boolean evaluate(Object object) {
                return !isEmpty(object);
            }

        });
    }

    public static String join(Object[] objects, String qualifier, String seperator) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < objects.length; ++i) {
            result.append(qualifier).append(objects[i]).append(qualifier);
            if (i < objects.length - 1)
                result.append(seperator);
        }
        return result.toString();
    }

    public static String join(Iterator objects, String qualifier, String seperator) {
        StringBuffer result = new StringBuffer();
        while (objects.hasNext()) {
            result.append(qualifier).append(objects.next()).append(qualifier);
            if (objects.hasNext()) result.append(seperator);
        }
        return result.toString();
    }

    public static String join(char[] objects, String qualifier, String seperator) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < objects.length; ++i) {
            result.append(qualifier).append(objects[i]).append(qualifier);
            if (i < objects.length - 1)
                result.append(seperator);
        }
        return result.toString();
    }

    public static String escapeDBString(Object string) {
        return StringUtil.replace(String.valueOf(string), SimpleConstants.DB_STRING_QUALIFIER, SimpleConstants.DB_STRING_QUALIFIER + SimpleConstants.DB_STRING_QUALIFIER);
    }

    public static boolean isValidPrecisionScale(String number, int precision, int scale) {
        try {
            BigDecimal decimal = new BigDecimal(number);
            String numberStrValue = decimal.toString();
            int indexOfDot = numberStrValue.indexOf('.');
            if (indexOfDot == -1) {
                return (numberStrValue.length() <= precision);
            } else {
                return (numberStrValue.length() - 1 <= precision && numberStrValue.substring(indexOfDot + 1).length() <= scale);
            }
        } catch (Exception e) {
            return false;
        }
    }

	public static String replace(String str, String pattern, String replace) {
		int s = 0;
		int e = 0;
		StringBuffer result = new StringBuffer();

		while ((e = str.indexOf(pattern, s)) >= 0) {
				result.append(str.substring(s, e));
				result.append(replace);
				s = e+pattern.length();
		 }

		result.append(str.substring(s));
		return result.toString();
	}

	public Object getValue(Map map, Object key, Object defaultValue) {
        return (map.containsKey(key)) ? map.get(key) : defaultValue;
    }

    public Object getValue(Map map, Object key) {
        return getValue(map, key, null);
    }

    public static int getInt(Object value, int defaultValue) {
        try {
            return (value == null) ? defaultValue : (value instanceof Number) ? ((Number) value).intValue() : Integer.parseInt(value.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static boolean isPrimitiveType(Object obj){
    	if (obj instanceof Boolean) {
    		return false;
    	} else if (obj instanceof Character){
    		return false;
    	} else if (obj instanceof Number){
    		return false;
    	} else if (obj instanceof String){
    		return false;
    	} else {
    		return true;
    	}
    }

    /*
     * Sample Code:
     * String user = (String)CommonUtil.decode(vo.getUpdateUser(), null, vo.getCreateUser(), vo.getUpdateUser());
     */
    public static Object decode(Object expression, Object searchValue, Object result1, Object result2){
    	Object rsltObj = null;
    	try{

    		if( (expression == null) || (isPrimitiveType(expression) && isPrimitiveType(searchValue)) ){
    			if(expression == searchValue){
        			rsltObj = result1;
        		} else {
        			rsltObj = result2;
        		}
    		} else {
	    		if(expression.equals(searchValue)){
	    			rsltObj = result1;
	    		} else {
	    			rsltObj = result2;
	    		}
    		}

    	} catch(Exception e){
    		Logger.logExceptions(e);
    		return null;
    	}

    	return rsltObj;
    }

    /*
     * Sample Code:
     * String[] searchValues = {"NEW", "CONFIRM", "COMPLETE", "CANCEL"};
     * String[] resultValues = {"Status is NEW", "Status is CONFIRM", "Status is COMPLETE", "Status is CANCEL"};
     * String decodedStatus = (String)CommonUtil.decode(vo.getHdrStatus(), searchValues, resultValues);
     */
    public static Object decode(Object expression, Object[] searchValues, Object[] resultValues){
    	return decode(expression, searchValues, resultValues, null);
    }

    /* Sample Code:
     * String[] searchValues = {"NEW", "CONFIRM", "COMPLETE", "CANCEL"};
     * String[] resultValues = {"Status is NEW", "Status is CONFIRM", "Status is COMPLETE", "Status is CANCEL"};
     * String defValue = "DEFAULT";
     * String decodedStatus = (String)CommonUtil.decode(vo.getHdrStatus(), searchValues, resultValues, defValue);
     */
    public static Object decode(Object expression, Object[] searchValues, Object[] resultValues, Object defValue){
    	Object rsltObj = null;
    	try{
    		if (searchValues.length != resultValues.length) {
    			throw new Exception("Error in incoming arguments");
    		}

    		boolean found = false;
    		for(int i = 0; (!found) && (i < searchValues.length); i++){
    			if( (expression == null) || ( isPrimitiveType(expression) && isPrimitiveType(searchValues[i])) ){
    				if(expression == searchValues[i]) {
		    			rsltObj = resultValues[i];
		    			found = true;
		    			break;
    				}
    			} else {
    				if(expression.equals(searchValues[i])) {
		    			rsltObj = resultValues[i];
		    			found = true;
		    			break;
    				}
	    		}
    		}

    		if(!found){
    			rsltObj = defValue;
    		}

    	} catch(Exception e){
    		Logger.logExceptions(e);
    		return null;
    	}

    	return rsltObj;
    }
    
    public static  ArrayList hashMapToArrayList(HashMap map){
    	ArrayList re = new ArrayList();
    	Set entries = map.entrySet(); 
    	Iterator iter = entries.iterator();
    	while(iter.hasNext())
    	{
    	   Map.Entry   entry   =   (Map.Entry)iter.next();
    	   Object   value   =   entry.getValue();
    	   re.add(value);
    	} 
    	return re;
    }
    
   public static String getPropertyStrIdx(String property){
	   String idx= "";
	   int preIdx = property.indexOf("[")+1;
	   int sufIdx = property.indexOf("]");
	   if(preIdx!=-1&&sufIdx!=-1&&property.indexOf(".")!=-1&&preIdx<sufIdx){
		 idx = property.substring(preIdx, sufIdx);   
	   }
	   return idx;
   }
}
